import Jimp from 'jimp';
import jsQR from 'jsqr';
import QrCode from 'qrcode-reader';
import fs from 'fs';

/**
 * 识别图片中的二维码
 * @param {string} imagePath - 图片路径
 * @returns {Promise<Object>} 识别结果
 */
export async function recognizeQRCode(imagePath) {
  try {
    // 检查文件是否存在
    if (!fs.existsSync(imagePath)) {
      return {
        success: false,
        error: '图片文件不存在'
      };
    }

    // 使用 Jimp 加载图片
    const image = await Jimp.read(imagePath);

    // 方法1: 使用 jsQR
    const jsQRResult = await recognizeWithJsQR(image);
    if (jsQRResult.success) {
      return jsQRResult;
    }

    // 方法2: 使用 qrcode-reader
    const qrReaderResult = await recognizeWithQRReader(image);
    if (qrReaderResult.success) {
      return qrReaderResult;
    }

    // 方法3: 尝试图像预处理后再识别
    const preprocessedResult = await recognizeWithPreprocessing(image);
    if (preprocessedResult.success) {
      return preprocessedResult;
    }

    return {
      success: false,
      error: '未识别到二维码'
    };

  } catch (error) {
    console.error('二维码识别错误:', error);
    return {
      success: false,
      error: error.message || '识别过程中发生错误'
    };
  }
}

/**
 * 使用 jsQR 识别
 * @param {Jimp} image - Jimp 图像对象
 * @returns {Promise<Object>} 识别结果
 */
async function recognizeWithJsQR(image) {
  try {
    const { data, width, height } = image.bitmap;

    // 转换为 RGBA 格式
    const imageData = new Uint8ClampedArray(data);

    // 尝试不同的识别参数
    const methods = ['attemptBoth', 'onlyInvert', 'dontInvert'];

    for (const method of methods) {
      const code = jsQR(imageData, width, height, {
        inversionAttempts: method,
      });

      if (code) {
        return {
          success: true,
          count: 1,
          data: [{
            text: code.data,
            location: {
              topLeft: code.location.topLeftCorner,
              topRight: code.location.topRightCorner,
              bottomLeft: code.location.bottomLeftCorner,
              bottomRight: code.location.bottomRightCorner
            },
            boundingBox: {
              x: code.location.topLeftCorner.x,
              y: code.location.topLeftCorner.y,
              width: code.location.topRightCorner.x - code.location.topLeftCorner.x,
              height: code.location.bottomLeftCorner.y - code.location.topLeftCorner.y
            }
          }]
        };
      }
    }

    return { success: false };
  } catch (error) {
    console.error('jsQR 识别错误:', error);
    return { success: false };
  }
}

/**
 * 使用 qrcode-reader 识别
 * @param {Jimp} image - Jimp 图像对象
 * @returns {Promise<Object>} 识别结果
 */
async function recognizeWithQRReader(image) {
  return new Promise((resolve) => {
    try {
      const qr = new QrCode();

      qr.callback = (err, value) => {
        if (err) {
          resolve({ success: false });
          return;
        }

        if (value && value.result) {
          resolve({
            success: true,
            count: 1,
            data: [{
              text: value.result,
              location: value.location || {},
              boundingBox: value.location ? {
                x: Math.min(...value.location.map(p => p.x)),
                y: Math.min(...value.location.map(p => p.y)),
                width: Math.max(...value.location.map(p => p.x)) - Math.min(...value.location.map(p => p.x)),
                height: Math.max(...value.location.map(p => p.y)) - Math.min(...value.location.map(p => p.y))
              } : {}
            }]
          });
        } else {
          resolve({ success: false });
        }
      };

      qr.decode(image.bitmap);
    } catch (error) {
      console.error('qrcode-reader 识别错误:', error);
      resolve({ success: false });
    }
  });
}

/**
 * 图像预处理后识别
 * @param {Jimp} originalImage - 原始图像
 * @returns {Promise<Object>} 识别结果
 */
async function recognizeWithPreprocessing(originalImage) {
  try {
    // 克隆图像以避免修改原图
    const image = originalImage.clone();

    // 预处理: 灰度化、增强对比度
    image
      .greyscale()
      .contrast(0.5)
      .normalize();

    // 再次尝试识别
    const result = await recognizeWithJsQR(image);
    if (result.success) {
      return result;
    }

    const result2 = await recognizeWithQRReader(image);
    if (result2.success) {
      return result2;
    }

    return { success: false };
  } catch (error) {
    console.error('预处理识别错误:', error);
    return { success: false };
  }
}

/**
 * 从 Buffer 识别二维码
 * @param {Buffer} buffer - 图片 Buffer
 * @returns {Promise<Object>} 识别结果
 */
export async function recognizeQRCodeFromBuffer(buffer) {
  try {
    const image = await Jimp.read(buffer);

    const jsQRResult = await recognizeWithJsQR(image);
    if (jsQRResult.success) {
      return jsQRResult;
    }

    const qrReaderResult = await recognizeWithQRReader(image);
    if (qrReaderResult.success) {
      return qrReaderResult;
    }

    return {
      success: false,
      error: '未识别到二维码'
    };

  } catch (error) {
    return {
      success: false,
      error: error.message || '识别过程中发生错误'
    };
  }
}

